<?php
class Upfiles extends Controller
{
	public function _default()
	{
		$file = $_FILES['NewFile'];
		$ext = $this->_getFileExt($file['name']);
		$filename = $this->_getFileName($ext);
		$result = move_uploaded_file($file['tmp_name'], ROOT_DIR . $filename);
		if($result){
			echo $this->SendUploadResults(0, '/' . $filename);
		}else{
			echo $this->SendUploadResults(1, '', '', '上传失败');
		}
		
	}
	
	public function show()
	{
		$this->display('upload_show.tpl');
	}
	
	public function ajaxUpload()
	{
		$dom = $_POST['dom'];
		$field = $_POST['field'];
		$file = $_FILES['file'];
		$ext = $this->_getFileExt($file['name']);
		$filename = $this->_getFileName($ext);
		$result = move_uploaded_file($file['tmp_name'], ROOT_DIR . $filename);
		$data = array(
			'dom'	=> $dom,
			'url'	=> APP_HOST . $filename,
			'field'	=> $field,
		);
		$re = json_encode($data);
		echo "<script type='text/javascript'>parent.re({$re});</script>";
	}
	
	function SendUploadResults( $errorNumber, $fileUrl = '', $fileName = '', $customMsg = '' )
	{
		echo "<script type=\"text/javascript\">";
		if ($errorNumber && $errorNumber != 201) {//1报错 0上传成功
			$fileUrl = "";
			$fileName = "";
		}
		$rpl = array( '\\' => '\\\\', '"' => '\\"' ) ;
		echo 'window.parent.OnUploadCompleted(' . $errorNumber . ',"' . strtr( $fileUrl, $rpl ) . '","' . strtr( $fileName, $rpl ) . '", "' . strtr( $customMsg, $rpl ) . '") ;' ;
		echo '</script>' ;
		exit ;
	}
	
	private function _getFileName($ext)
	{
		$path = $this->_getFilePath();
		$filename = $path . date('YmdHis', time()) . '.' . $ext;
		while(file_exists(ROOT_DIR . $filename)){
			$filename = $path . date('YmdHis', time()) . '_' . rand(0, 999) . '.' . $ext;
		}
		return $filename;
	}
	
	private function _getFilePath()
	{
		$path = date('Ym', time());
		$baseDir = ROOT_DIR . 'Upload/';
		if (!is_dir($baseDir)){
			mkdir($baseDir, 0777);
		}
		if (!is_dir($baseDir . $path)){
			mkdir($baseDir . $path, '0777');
		}
		return 'Upload/' . $path . '/';
	}
	
	private function _getFileExt($filename)
	{
		$file_ext_name = '';
		$dot_pos = stripos($filename, '.');
		$file_ext_name = substr($filename, $dot_pos+1);
		return $file_ext_name;	
	}
}